<?php
/**
 * Created by PhpStorm.
 * User: CPR137
 * Date: 2018/1/25
 * Time: 9:54
 */
/**
 * 获取图片
 *
 * @param $name
 * @return string
 */
function getImage($name, $size = '')
{
    if (empty($name)) {
        return '/static/default.jpg';
    }
    $uploadPath = C('UPLOAD_PATH');
    $staticPath = C('STATIC_PATH');
    $staticUrl = '/';
    $imagePath = $uploadPath . '/' . $name;
    if (!empty($size)) {
        $handName = function ($name, $size) {
            $names = explode('.', $name);
            $ext = array_pop($names);
            $newName = array_pop($names);
            return implode('.', array($newName . $size, $ext));
        };
        $imageName = $handName($name, $size);
        $thumbPath = $uploadPath . '/' . $imageName;
        if (file_exists($imagePath) && !file_exists($thumbPath)) {
            $_size = explode('_', substr($size, 1));
            $imageManage = new \Intervention\Image\ImageManager(array('driver' => 'gd'));
            $imageManage->make($imagePath)
                ->resize($_size[0], $_size[1])
                ->save($thumbPath);
        }
        $imagePath = $thumbPath;
    }
    $_image = str_replace($staticPath, $staticUrl, $imagePath);
    return $_image;
}

/**
 * 获取上传存储路径
 *
 * @param string $mode
 * @return string|type
 */
function getFilePath($mode = '')
{
    $uploadPath = C('UPLOAD_PATH');
    switch ($mode) {
        case 'cms':
            $uploadPath .= '/cms';
            break;
        case 'ad':
            $uploadPath .= '/ad';
            break;
        default:
            $uploadPath .= '';
    }
    return $uploadPath;
}

/**
 * 无线分类 一层结构
 * @param $cate
 * @param int $pid
 * @param int $layer
 * @param string $placeHolder
 * @param string $placeHolderBegin
 * @return array
 */
function treeStructForLevel($cate, $pid = 0, $layer = 0, $placeHolder = '--', $placeHolderBegin = '|')
{
    static $data = [];
    foreach ($cate as $value) {
        if ($value['pid'] == $pid) {
            $placeHolderBegin = $layer == 0 ? '' : $placeHolderBegin;
            $value['placeHolder'] = $placeHolderBegin . str_repeat($placeHolder, $layer);
            $data[] = $value;
            treeStructForLevel($cate, $value['id'], $layer + 1);
        }
    }
    return $data;
}


function treeStructForLayer($cate, $pid = 0)
{
    $data = [];
    foreach ($cate as $value) {
        if ($value['pid'] == $pid) {
            $value['sub'] = treeStructForLayer($cate, $value['id']);
            $data[] = $value;
        }
    }
    return $data;
}

function getParents($cate, $id)
{
    static $data = [];
    foreach ($cate as $value) {
        if ($value['id'] == $id) {
            $data[] = $value;
            getParents($cate, $value['pid']);
        }
    }
    $sort = array_column($data, 'id');
    array_multisort($sort, $data, SORT_ASC);
    return $data;
}

function getChilden($cate, $id)
{
    static $data = [];
    foreach ($cate as $value) {
        if ($value['pid'] == $id) {
            $data[] = $value;
            getChilden($cate, $value['id']);
        }
    }
    return $data;
}

/**
 * 获取日期时间
 * @param string $format
 * @return bool|string
 */
function getDateTime($format = 'Y-m-d H:i:s')
{
    return date($format, time());
}


/**
 * 生成itemId
 * @return string
 */
function getItemId()
{
    $hour = date('z') * 24 + date('H');
    $hour = str_repeat('0', 4 - strlen($hour)) . $hour;
    //	echo date('y') . $hour . PHP_EOL;
    return date('y') . $hour . getRandNumber(10);
}

/**
 * 生成固定长度的随机数
 *
 * @param int $length
 * @return string
 */
function getRandNumber($length = 6)
{
    $num = '';
    if ($length >= 10) {
        $t = intval($length / 9);
        $tail = $length % 9;
        for ($i = 1; $i <= $t; $i++) {
            $num .= substr(mt_rand('1' . str_repeat('0', 9), str_repeat('9', 10)), 1);
        }
        $num .= substr(mt_rand('1' . str_repeat('0', $tail), str_repeat('9', $tail + 1)), 1);
        return $num;
    } else {
        return substr(mt_rand('1' . str_repeat('0', $length), str_repeat('9', $length + 1)), 1);
    }
}


///**
// * 请求接口方法
// * @param $url
// * @param array $data
// * @param string $mode
// * @param string $method
// * @return mixed
// */
//function apiRequest($url, $data = [], $mode = 'Api', $method = 'get')
//{
//    if ($mode == 'Api') {
//        $host = C('HOME_URL');
//    }
//    if (empty($host)) {
//        trigger_error('接口地址不存在');
//    }
//    #生产环境接口加密
//    if (ENVIRONMENT !== 'develop') {
//        $dex3 = new metacms\base\Dex3();
//        $encode_data = base64_encode($dex3->encrypt(json_encode($data)));
//        $data = [
//            'param' => $encode_data
//        ];
//    }
//    if ($method == 'get') {
//        #返回缓存内容
//        $cache_key = md5(json_encode($data));
//        $cache_name = $url;
//        $cache_time = ENVIRONMENT == 'product' ? 300 : 1;
//        if (\metacms\base\Application::cache($cache_name)->isCached($cache_key) && C('CACHEING')) {
//            $result = \metacms\base\Application::cache($cache_name)->retrieve($cache_key);
//        } else {
//            $url = $host . U('api/' . $url, $data);
//            $response = curl()->get($url);
//            if (!is_object($response)) {
//                trigger_error('接口请求错误');
//            }
//            $result = json_decode(json_encode($response), true);
//            if (isset($result['cached']) && $result['cached']) {
//                \metacms\base\Application::cache($cache_name)->store($cache_key, $result, $cache_time);
//                \metacms\base\Application::cache($cache_name)->eraseExpired();
//            }
//        }
//    }
//    return $result;
//}


function main_image($request_data)
{
    $field = 'main_image';
    $model_id = $request_data['model_id'];
    $main_image = isset($request_data['main_image']) ? $request_data['main_image'] : '';
    if ($model_id == 2 && empty($main_image)) {
        $content = htmlspecialchars_decode($request_data['content']);
        $img = getImageFromContent($content);
        if ($img) {
            $request_data[$field] = getImageUrlFromUrl(current($img));
        }
    }
    return $request_data;
}

hooks()->add_filter('publish_post', 'main_image');


function getImageFromContent($content)
{
    //匹配IMG标签
    $content = htmlspecialchars_decode($content);
    $img_pattern = "/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i";
    preg_match_all($img_pattern, $content, $img_out);
    return $img_out[2];
}

function getImageUrlFromUrl($url)
{
    $_url = explode('/', $url);
    return end($_url);
}

/**
 * 获取uuid
 * @access public
 * @author furong
 * @return \app\modules\admin\models\type
 * @since 2018年1月3日 10:41:22
 * @abstract
 */
function uuid()
{
    $model = new \app\modules\admin\models\AdminUser();
    return $model->getUserId();
}

/**
 * 获取客户端ip
 * @return string
 */
function getClientIp()
{
    if ($_SERVER["REMOTE_ADDR"])
        $ip = $_SERVER["REMOTE_ADDR"];
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknown";
    return $ip;
}

/**
 * 打印数组 调试用
 * @param type $var
 */
function print_g($var)
{
    echo "<pre>";
    print_r($var);
    echo "</pre>";
    exit();
}

/**
 * 递归创建多级目录
 * @param type $dirPath
 * @param type $mode
 * @return boolean
 */
function mkdirs($dirPath, $mode = 0777)
{
    if (!is_dir($dirPath)) {
        if (!mkdirs(dirname($dirPath))) {
            return FALSE;
        }
        if (!mkdir($dirPath, $mode)) {
            return FALSE;
        }
    }
    return TRUE;
}

/**
 * 创建文件
 * @param type $filePath 文件路径
 * @param type $content 文件内容
 * @return boolean
 */
function mkFile($filePath, $content)
{
    if (is_file($filePath))
        return true;
    mkdirs(dirname($filePath));
    $handle = fopen($filePath, 'w');
    if (!$handle)
        return FALSE;
    if (!fwrite($handle, $content))
        return false;
    fclose($handle);
    return true;
}

/**
 * 框架内置打印调试信息函数
 * @param type $var
 */
function dump($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}


/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suff = true)
{
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    if (mb_strlen($str, 'utf8') > $length && $suff) {
        return $slice . '...';
    } else {
        return $slice;
    }
}

/**
 * 组装url
 * @param $url
 * @param array $parm
 * @return string
 */
function U($url, $parm = array())
{
    $url = explode('/', $url);
    foreach ($url as $key => $value) {
        $url[$key] = snake($value, '-');
    }
    $url = join('/', $url);
    array_unshift($parm, $url);
    return urldecode(Yii::$app->urlManager->createUrl($parm));
}

/**
 * Convert a string to snake case.
 *
 * @param  string $value
 * @param  string $delimiter
 * @return string
 */
function snake($value, $delimiter = '_')
{
    $replace = '$1' . $delimiter . '$2';
    return ctype_lower($value) ? $value : strtolower(preg_replace('/(.)([A-Z])/', $replace, $value));
}

/**
 * 框架getConfig方法 别名函数
 * @param type $configName
 * @return type
 */
function C($key = '')
{
    $param = Yii::$app->params;
    if (!$key) {
        return $param;
    } else {
        if (isset($param[$key])) {
            return $param[$key];
        } else {
            throw  new \Exception('"' . $key . '"配置不存在');
        }
    }
}

/**
 * @author furong
 * @return Hooks
 * @since ${DATE}
 * @abstract
 */
function hooks()
{
    global $hooks;
    return $hooks;
}

function apiRequest($url, $data = [], $mode = 'Api', $method = 'get')
{
    if ($mode == 'Api') {
        $host = 'http://' . $_SERVER['HTTP_HOST'];
        $url = 'api/' . $url;
    }
    if (empty($host)) {
        trigger_error('接口地址不存在');
    }
    #生产环境接口加密
    $key = C('API_ENCRYPTION_KEY');
    if ($key) {
        $dex3 = new \app\modules\common\Des3($key);
        $encode_data = base64_encode($dex3->encrypt(json_encode($data)));
        $data = [
            'param' => $encode_data
        ];
    }
    if ($method == 'get') {
        #返回缓存内容
        $url = $host . U($url, $data);
        $cache_name = md5($url);
        if (\Yii::$app->cache->exists($cache_name) and c('CACHE_OPEN')) {
            $result = \Yii::$app->cache->get($cache_name);
        } else {
            $param = [
                'base_uri' => $host,
                'proxy' => []
            ];
            if (C('CURLOPT_PROXY')) {
                $param['proxy']['http'] = C('CURLOPT_PROXY');
            }
            $client = new \GuzzleHttp\Client();
            $response = $client->request('GET', $url);
//            if ($curl->error) {
//                throw  new \Exception('接口请求错误:' . $curl->error);
//            }

            $result = json_decode($response->getBody()->getContents(), true);
            if (isset($result['cached']) && $result['cached']) {
                \Yii::$app->cache->add($cache_name, $result, 300);
            }
        }
    }
    return $result;
}

/**
 * @return \Curl\Curl
 */
function curl()
{
    $curl = \app\modules\common\Message::getInfo('curl');
    if (!$curl) {
        $curl = new \Curl\Curl();
        $curlopt_proxy = C('CURLOPT_PROXY');
        if ($curlopt_proxy) {
            $curl->setOpt(CURLOPT_PROXY, $curlopt_proxy);
        }
        $curl->setOpt(CURLOPT_TIMEOUT, 60);
        \app\modules\common\Message::setInfo('curl', $curl);
    }
    return $curl;
}
